import { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Row, Col, Avatar, Upload, Modal, Spin, Tabs, App } from 'antd';
import { UserOutlined, LockOutlined, PhoneOutlined, IdcardOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import ImgCrop from 'antd-img-crop';
import imageCompression from 'browser-image-compression';
import { getUserById } from '@/api/user';
import { changePasswordApi,updateUserInfoApi } from '@/api/login';
import { setUserInfo } from '@/store/user';
import store from '@/store';

const MyIndex = () => {
    const [form] = Form.useForm();
    const [passwordForm] = Form.useForm();
    const dispatch = useDispatch();
    const userInfo = useSelector(state => state.user.userInfo);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fullUserInfo, setFullUserInfo] = useState(null);
    const [loading, setLoading] = useState(true);
    const [fileList, setFileList] = useState([]);
    const { message } = App.useApp();
    const state = store.getState();
    const token = state.user.token;

    // 获取完整的用户信息
    useEffect(() => {
        getUserById(userInfo.userId).then(res => {
            setFullUserInfo(res.data);
            // 初始化头像文件列表
            if (res.data.avatar) {
                setFileList([{
                    uid: '-1',
                    name: 'avatar.png',
                    status: 'done',
                    url: res.data.avatar,
                    thumbUrl: res.data.avatar
                }]);
            }
        }).finally(() => {
            setLoading(false);
        });
    }, []);

    // 处理密码修改
    const onFinishPassword = (values) => {
        if (values.newPassword !== values.confirmPassword) {
            message.error('两次输入的新密码不一致');
            return;
        }

        changePasswordApi({
            oldPassword: values.oldPassword,
            newPassword: values.newPassword
        }).then(() => {
                message.success('密码修改成功，请重新登录');
                // 清除store中的用户信息并跳转到登录页
                dispatch(setUserInfo(null));
                store.dispatch({ type: 'user/logout' });
                window.location.href = '/login';
        })
    };

    // 处理基础信息修改
    const onFinishBasic = (values) => {
        updateUserInfoApi(values).then(() => {
            message.success('修改成功');
            // 刷新用户信息
            getUserById(userInfo.userId).then(res => {
                setFullUserInfo(res.data);
                const newUserInfo = {
                    avatar: res.data.avatar,
                    username: res.data.username,
                    nickname: res.data.nickname,
                    userId: res.data.userId,
                    token: null
                }
                dispatch(setUserInfo(newUserInfo));
            });
        });
    };

    // 上传头像相关函数
    const handlePreview = async (file) => {
        let src = file.url;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj);
                reader.onload = () => resolve(reader.result);
            });
        }
        setPreviewImage(src);
        setPreviewOpen(true);
    };

    const handleChange = ({ fileList: newFileList, file }) => {
        if (file.status === undefined) {
            newFileList = [];
        }

        if (file.status === 'done') {
            const result = file.response;
            if (result.code == 200) {
                // 更新表单中的avatar字段
                form.setFieldsValue({ avatar: result.data });
            } else {
                newFileList = [];
                form.setFieldsValue({ avatar: '' });
                message.error(result.msg || '上传失败');
            }
        }
        setFileList(newFileList);
    };

    const handleRemove = (file) => {
        const index = fileList.indexOf(file);
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        setFileList(newFileList);
        form.setFieldsValue({ avatar: '' });
    };

    const beforeUpload = async (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 格式的文件!');
            return false;
        }

        // 压缩图片
        const options = {
            maxSizeMB: 0.5, // 最大 500KB
            maxWidthOrHeight: 200, // 最大宽度或高度为 200px
            useWebWorker: false,
        };

        try {
            // 压缩图片
            const compressedFile = await imageCompression(file, options);

            // 检查压缩后的文件大小
            const isLt500kb = compressedFile.size / 1024 < 500;
            if (!isLt500kb) {
                message.error('头像大小压缩后仍然超过 500kb!');
                return false;
            }

            // 返回压缩后的文件
            return compressedFile;
        } catch (error) {
            console.error('图片压缩失败:', error);
            message.error('图片压缩失败!');
            return false;
        }
    };

    const items = [
        {
            key: '1',
            label: '修改密码',
            children: (
                <Card>
                    <Form
                        form={passwordForm}
                        layout="vertical"
                        onFinish={onFinishPassword}
                    >
                        <Form.Item
                            name="oldPassword"
                            label="原密码"
                            rules={[{ required: true, message: '请输入原密码!' }]}
                        >
                            <Input.Password prefix={<LockOutlined />} placeholder="原密码" />
                        </Form.Item>

                        <Form.Item
                            name="newPassword"
                            label="新密码"
                            rules={[
                                { required: true, message: '请输入新密码!' },
                                { min: 6, message: '密码长度不能少于6位' }
                            ]}
                        >
                            <Input.Password prefix={<LockOutlined />} placeholder="新密码" />
                        </Form.Item>

                        <Form.Item
                            name="confirmPassword"
                            label="确认新密码"
                            dependencies={['newPassword']}
                            rules={[
                                { required: true, message: '请确认新密码!' },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('newPassword') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('两次输入的密码不一致!'));
                                    },
                                }),
                            ]}
                        >
                            <Input.Password prefix={<LockOutlined />} placeholder="确认新密码" />
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                修改密码
                            </Button>
                        </Form.Item>
                    </Form>
                </Card>
            ),
        },
        {
            key: '2',
            label: '基础信息',
            children: (
                <Card>
                    <Form
                        form={form}
                        layout="vertical"
                        onFinish={onFinishBasic}
                        initialValues={{
                            username: fullUserInfo?.username || userInfo?.username,
                            nickname: fullUserInfo?.nickname || userInfo?.nickname,
                            phone: fullUserInfo?.phone || userInfo?.phone,
                            avatar: fullUserInfo?.avatar || userInfo?.avatar
                        }}
                    >
                        <Form.Item 
                            name="avatar" 
                            label="头像"
                            rules={[{ required: true, message: '请上传头像!' }]}
                        >
                            <ImgCrop rotationSlider>
                                <Upload
                                    headers={{
                                        Authorization: token,
                                    }}
                                    action="/file/upload"
                                    listType="picture-card"
                                    fileList={fileList}
                                    beforeUpload={beforeUpload}
                                    onChange={handleChange}
                                    onPreview={handlePreview}
                                    onRemove={handleRemove}
                                >
                                    {fileList.length < 1 && '+ 上传'}
                                </Upload>
                            </ImgCrop>
                        </Form.Item>

                        <Form.Item
                            name="username"
                            label="用户名"
                            rules={[{ required: true, message: '请输入用户名!' }]}
                        >
                            <Input prefix={<IdcardOutlined />} placeholder="用户名" disabled />
                        </Form.Item>

                        <Form.Item
                            name="nickname"
                            label="昵称"
                            rules={[{ required: true, message: '请输入昵称!' }]}
                        >
                            <Input placeholder="昵称" />
                        </Form.Item>

                        <Form.Item
                            name="phone"
                            label="手机号"
                            rules={[{ required: true, message: '请输入手机号!' }]}
                        >
                            <Input prefix={<PhoneOutlined />} placeholder="手机号" />
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                保存信息
                            </Button>
                        </Form.Item>
                    </Form>
                </Card>
            ),
        }
    ];

    return (
        <div style={{ padding: '20px' }}>
            {loading ? (
                <div style={{ textAlign: 'center', padding: '50px' }}>
                    <Spin size="large" />
                </div>
            ) : (
                <Row gutter={[20, 20]}>
                    {/* 左侧：个人信息展示 */}
                    <Col span={8}>
                        <Card style={{ height: '100%' }}>
                            <div style={{ textAlign: 'center', marginBottom: 24 }}>
                                <Avatar
                                    size={100}
                                    src={fullUserInfo?.avatar || userInfo?.avatar}
                                    icon={<UserOutlined />}
                                />
                            </div>

                            <div style={{ padding: '0 20px' }}>
                                <div style={{ display: 'flex', alignItems: 'center', margin: '16px 0' }}>
                                    <IdcardOutlined style={{ fontSize: '18px', marginRight: 10, color: '#1890ff' }} />
                                    <span style={{ fontSize: '16px' }}>{fullUserInfo?.username || userInfo?.username}</span>
                                </div>

                                <div style={{ display: 'flex', alignItems: 'center', margin: '16px 0' }}>
                                    <UserOutlined style={{ fontSize: '18px', marginRight: 10, color: '#52c41a' }} />
                                    <span style={{ fontSize: '16px' }}>{fullUserInfo?.nickname || userInfo?.nickname || '暂无昵称'}</span>
                                </div>

                                <div style={{ display: 'flex', alignItems: 'center', margin: '16px 0' }}>
                                    <PhoneOutlined style={{ fontSize: '18px', marginRight: 10, color: '#722ed1' }} />
                                    <span style={{ fontSize: '16px' }}>{fullUserInfo?.phone || userInfo?.phone || '暂无手机号'}</span>
                                </div>
                            </div>
                        </Card>
                    </Col>

                    {/* 右侧：信息修改Tabs */}
                    <Col span={16}>
                        <Card style={{ height: '100%' }}>
                            <Tabs defaultActiveKey="1" items={items} />
                        </Card>
                    </Col>
                </Row>
            )}

            <Modal
                open={previewOpen}
                title="头像预览"
                footer={null}
                onCancel={() => setPreviewOpen(false)}
            >
                <img alt="头像预览" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </div>
    );
};

export default MyIndex;